package org.realogic.cfm.util;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateParser implements Serializable {

	private static final long serialVersionUID = -6897534819654972183L;

	private SimpleDateFormat[] hypenFormatterList;

	private SimpleDateFormat[] slashFormatterList;

	public DateParser() {
		initHypenList();
		initSlashList();
	}

	public java.sql.Timestamp parseTimestamp(String formatedDate) {
		java.util.Date d = parse(formatedDate);
		if (d == null) {
			throw new RuntimeException("Could not parse timestamp [" + formatedDate + "]");
		} else {
			return new java.sql.Timestamp(d.getTime());
		}
	}

	public java.sql.Date parseDate(String formatedDate) {
		java.util.Date d = parse(formatedDate);
		if (d == null) {
			throw new RuntimeException("Could not parse date [" + formatedDate + "]");
		} else {
			return new java.sql.Date(d.getTime());
		}
	}

	public java.util.Date parse(String formatedDate) {
		if (formatedDate == null) {
			return null;
		}
		int length = formatedDate.length();
		// assume its a short date format
		int formatType = 0;
		if (length > 19) {
			// its long format with millis
			formatType = 2;
		} else if (length > 10) {
			// its long format but no millis
			formatType = 1;
		}

		boolean isHypen = formatedDate.indexOf('-') > -1;
		SimpleDateFormat formatter = null;
		if (isHypen) {
			formatter = hypenFormatterList[formatType];
		} else {
			// if not hypen assuming a slash is used
			formatter = slashFormatterList[formatType];
		}
		try {
			synchronized (formatter) {
				return formatter.parse(formatedDate);
			}
		} catch (ParseException ex) {
			throw new RuntimeException("Format of date [" + formatedDate + "] errored", ex);
		}
	}

	private void initHypenList() {
		hypenFormatterList = new SimpleDateFormat[3];
		hypenFormatterList[0] = new SimpleDateFormat("yyyy-MM-dd");
		hypenFormatterList[1] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		hypenFormatterList[2] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
	}

	private void initSlashList() {
		slashFormatterList = new SimpleDateFormat[3];
		slashFormatterList[0] = new SimpleDateFormat("yyyy/MM/dd");
		slashFormatterList[1] = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		slashFormatterList[2] = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.S");
	}

}
